package pre.lxm.demo.keyboard;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import pre.lxm.demo.R;
import pre.lxm.demo.chart.DisplayUtil;


public class CustomKeyboard extends RelativeLayout {
    private static final String TAG = "CustomKeyboard";

    private String[] txtStrings = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", ""};
    private Paint mPaint;
    private ArrayList<TextView> tvList;

    private String[] colors = new String[]{"#FF0000", "#FF00F0", "#0000FF",
            "#FFF000", "#00FF00", "#00FFFF",
            "#FF00FF", "#FF0F00", "#FFFF00", "#FFF000", "#00FF00", "#00FFFF"};
    //隐藏栏的高度
    private int arrowHeight = 30;
    private int mPaintWidth = DisplayUtil.dip2px(getContext(), 1);
    private Activity mActivity;

    private Animation enterAnim, exitAnim;
    private ImageView arrowIv;
    private EditText mEditText;

    public CustomKeyboard(Context context) {
        this(context, null);
    }

    public CustomKeyboard(Context context, AttributeSet attrs) {
        super(context, attrs);
        mActivity = (Activity) context;
        init();
    }


    private void init() {
        setBackgroundColor(Color.WHITE);
        tvList = new ArrayList<>();
        arrowHeight = dp2px(arrowHeight);
        initPaint();
        enterAnim = AnimationUtils.loadAnimation(getContext(), R.anim.push_bottom_in);
        exitAnim = AnimationUtils.loadAnimation(getContext(), R.anim.push_bottom_out);

    }

    private int itemWidth, itemHeight;

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        itemWidth = (getWidth() - mPaintWidth * 4) / 3;
        itemHeight = (getHeight() - arrowHeight - mPaintWidth * 5) / 4;
        addArrowLayout();
        addTextView();
        addImageView();
    }

    private void addImageView() {
        ImageView deleteIv = new ImageView(getContext());
        TextView mTv = tvList.get(tvList.size() - 1);
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) mTv.getLayoutParams();
        RelativeLayout.LayoutParams ivRlp = new RelativeLayout.LayoutParams(rlp.width, rlp.height);
        ivRlp.addRule(RelativeLayout.ALIGN_TOP, mTv.getId());
        ivRlp.addRule(RelativeLayout.RIGHT_OF, mTv.getId());
        ivRlp.leftMargin = mPaintWidth;
        deleteIv.setImageResource(R.mipmap.keyboard_delete_img);
        deleteIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        addView(deleteIv, ivRlp);
        deleteIv.setLayoutParams(ivRlp);
        deleteIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditText.setText(mEditText.getText().subSequence(0, mEditText.getText().length()-1));
                mEditText.setSelection(mEditText.getText().length());
            }
        });
    }


    private void addTextView() {
        int length = txtStrings.length;
        for (int i = 0; i < length - 1; i++) {
            final TextView mTv = new TextView(getContext());
            mTv.setText(txtStrings[i]);
            mTv.setTextColor(Color.BLACK);
            mTv.setTextSize(30);
            mTv.setGravity(Gravity.CENTER);
//            mTv.setBackgroundDrawable(createDrawable());
            mTv.setBackgroundDrawable(createSelectorDrawable());
//            mTv.setBackgroundColor(Color.parseColor(colors[i]));
//            mTv.setBackgroundResource(R.drawable.selector_gird_item);
            mTv.setClickable(true);
            mTv.setId(i + 1);
            tvList.add(mTv);
            mTv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    StringBuilder sBuilder = new StringBuilder(mEditText.getText().toString());
                    sBuilder.append(mTv.getText().toString());
                    mEditText.setText(sBuilder.toString());
                    mEditText.setSelection(sBuilder.length());
                }
            });


            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            rlp.width = itemWidth;
            rlp.height = itemHeight;
            if ((i + 1) % 3 == 1) {
                rlp.leftMargin = mPaintWidth;
                rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                if (i == 0) {
                    rlp.topMargin = arrowHeight + 2 * mPaintWidth;
                } else {
                    rlp.topMargin = mPaintWidth;
                }
            } else {
                rlp.addRule(RelativeLayout.ALIGN_TOP, tvList.get(i - 1).getId());
                rlp.addRule(RelativeLayout.RIGHT_OF, tvList.get(i - 1).getId());
                rlp.leftMargin = mPaintWidth;
            }
            if (i >= 3) {
                rlp.addRule(RelativeLayout.BELOW, tvList.get(i - 3).getId());
            }
            addView(mTv, rlp);
            mTv.setLayoutParams(rlp);
        }
    }


    private void addArrowLayout() {

        arrowIv = new ImageView(getContext());
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                arrowHeight);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        arrowIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        arrowIv.setImageResource(R.mipmap.keyboard_back_img);
        arrowIv.setLayoutParams(rlp);
        addView(arrowIv, rlp);
        arrowIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startAnimation(exitAnim);
                setVisibility(View.GONE);
            }
        });
    }

    private Drawable createDrawable(int color) {
        GradientDrawable gDrawable = new GradientDrawable();
        gDrawable.setShape(GradientDrawable.RECTANGLE);
        gDrawable.setColor(color);//Color.parseColor("#E0E0E0")
        return gDrawable;
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStrokeWidth(mPaintWidth);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.parseColor("#D0D0D0"));
    }

    private Drawable createSelectorDrawable() {
        StateListDrawable mStateDrawable = new StateListDrawable();
        mStateDrawable.addState(new int[]{android.R.attr.state_pressed}, createDrawable(Color.parseColor("#C0C4C7")));
        mStateDrawable.addState(new int[]{android.R.attr.state_selected}, createDrawable(Color.parseColor
                ("#C0C4C7")));
//        mStateDrawable.addState(new int[]{-android.R.attr.state_enabled}, createDrawable(Color.parseColor
// ("#C0C4C7")));
//        mStateDrawable.addState(new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed}, createDrawable
//                (Color.parseColor("#F5F5F5")));
//        mStateDrawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}, createDrawable
//                (Color
//                        .parseColor("#C0C4C7")));
        return mStateDrawable;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        int itemWidth = tvList.get(0).getWidth();
        int itemHeight = tvList.get(0).getHeight();
        for (int i = 0; i < 4; i++) {
            //横线 4根
            canvas.drawLine(0, mPaintWidth * (i + 1) + itemHeight * i + arrowHeight, getWidth(),
                    mPaintWidth * (i + 1) + itemHeight * i + arrowHeight, mPaint);
            //竖线 2根
            if (i > 0 && i < 3) {
                canvas.drawLine(mPaintWidth * (i + 1) + itemWidth * i, arrowHeight, mPaintWidth * (i + 1) + itemWidth
                        * i, getHeight(), mPaint);
            }
        }
    }


    private int dp2px(float dipValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    public void setEdittext(final EditText et) {
        mEditText = et;
        setVisibility(View.GONE);
        if (Build.VERSION.SDK_INT <= 10) {
            et.setInputType(InputType.TYPE_NULL);
        } else {
            mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(et, false);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        et.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setFocusable(true);
                setFocusableInTouchMode(true);
                startAnimation(enterAnim);
                setVisibility(View.VISIBLE);
            }
        });
    }

}
